package me.sdevil507.activemq.async;

import lombok.extern.slf4j.Slf4j;
import me.sdevil507.activemq.QueueName;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 异步消息消费者
 *
 * @author sdevil507
 */
@Component
@Slf4j
public class AsyncCustomer {

    /**
     * 异步接收消息
     * <p>
     * 开启最低5个线程同时处理
     *
     * @param id 唯一key
     * @return 异步消息返回
     */
    @JmsListener(destination = QueueName.ASYNC, concurrency = "5-20")
    @SendTo(QueueName.ASYNC_RESULT)
    public String receiveMessage(String id) {
        // 产生随机值
        int result = new Random().nextInt(10);
        result += 1;
        try {
            // 首先接收消息
            System.out.println("收到消息:" + id);
            // 模拟耗时操作
            Thread.sleep(result * 1000);
            System.out.println("处理了消息:" + id + ",用时:" + result + "秒");
            return "处理了消息:" + id + ",用时:" + result + "秒";
        } catch (Exception e) {
            log.error("消息处理失败:", e);
            return null;
        }
    }
}
